<?php

namespace App\Services\Assess;

use App\Models\Assess\VisitorsRecordModel;
use App\Services\BaseService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

class VisitorsRecordService extends BaseService
{

    //国家
    public $country = ['美国', '巴西', '加拿大', '墨西哥', '阿拉伯', '沙特阿拉伯', '英国', '德国', '西班牙', '法国', '比利时', '印度', '意大利', '土耳其', '澳大利亚', '日本', '新加坡', '荷兰', '中国'];
    //域名
    public $referrer = [
        'orfeldtech.com/pages/warranty',
        'orfeldshop.com',
        'orfeldwarranty.com'
    ];
    //ip类型(1:正常用户,2:恶意用户)
    public $ipType = [
        1=>'正常访客',
        2=>'恶意访客'
    ];

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new VisitorsRecordModel();
    }

    //获取配置项
    public function getVisitorConfig()
    {
        $config = [];
        $config['country_list'] = $this->country;
        $config['referrer_list'] = $this->referrer;
        $config['ip_type_list'] = $this->ipType;
        return $config;
    }


    public function getList()
    {
        $param = request()->all();

        // 上级ID
        $ip = getter($param, 'ip', '');
        $country = getter($param, 'country', '');
        $referrer = getter($param, 'referrer', '');
        $ipType = getter($param, 'ip_type', 1);
        $sort = getter($param, 'sort', 'create_time');
        $order = getter($param, 'order', 'desc');
        $time = getter($param, 'time', []);
        $page_size = getter($param, 'page', 1);
        $limit = getter($param, 'limit', 10);

        if (!empty($ip)) $map[] = ['ip', '=', $ip];
        if (!empty($time)) {
            if (!empty($time[0])) $map[] = ['create_time', '>=', strtotime($time[0])];
            if (!empty($time[1])) $map[] = ['create_time', '<=', strtotime($time[1])];
        }
        if (!empty($country))  $map[] = ['country', '=', $country];
        if (!empty($referrer)) $map[] = ["referrer", 'like', "%{$referrer}%"];

        $offset = ($page_size - 1) * $limit;

        if ($ipType ==1){
            // 查询条件
            $map[] = ['mark','=',1];
        }else{
            $map[] = ['mark','=',0];
            $map[] = ['ip_type','=',2];
        }
        $model2 = $this->model->where($map);
        if ($ipType ==1 ){
            $model2->whereIn('ip_type',[0,1]);
            $map[] = ['ip_type','in',[0,1]];
        }
        $count = $model2->count();
        $list = $this->model->getList($map, [['create_time', 'desc']],"{$offset},{$limit}",false,true);

        return array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "count" => $count,
        );

    }


    public function setVisitorsRecord()
    {
        $param = request()->all();
//        $response = curl_get('https://ip.useragentinfo.com/json');
//        if (!empty($response)) $response = json_decode($response, true);
//        $responseData = $response ?? [];
        $data = [
            'ip' => $param['ip'] ?? request()->ip(),
            'country' => $param['country'] ?? '',
            'province' => $param['province'] ?? '',
            'city' => $param['city'] ?? '',
            'area' => $param['area'] ?? '',
            'is_mobile' => $param['is_mobile'] ?? 0,
            'referrer' => $param['origin'] ?? ($_SERVER['HTTP_REFERER'] ?? ''),
            'create_time' => time(),
            'update_time' => time()
        ];

        # 如果是阿里云网站检测 蜘蛛采集等操作 直接返回
        $ips = [
            '47.92.72.15','47.92.68.55','8.142.42.74','47.92.79.71','47.92.78.102','39.103.133.249','47.92.30.214','27.115.124.101','27.115.124.109',
            '27.115.124.53','39.103.133.249','47.92.29.136','47.92.30.57','47.92.31.57','47.92.32.64','47.92.33.204','47.92.36.178','47.92.37.1',
            '47.92.5.239','47.92.67.105','47.92.70.66','47.92.73.109','47.92.77.114','47.92.79.86','66.249.79.129','66.249.79.133','66.249.79.134',
            '66.249.79.135','66.249.79.142','8.142.167.31','8.142.31.72','8.142.87.162'
        ];
        if (in_array($data['ip'],$ips)){
            return message("操作成功", true, ['record_id' => 0]);
        }


        $userAgent = request()->userAgent();
        $browser = '';

        if (strpos($userAgent, 'Windows NT') !== false) {
            $visitorsPlatform = 'Windows';
        } elseif (strpos($userAgent, 'Android') !== false) {
            $visitorsPlatform = 'Android';
        } elseif (strpos($userAgent, 'iPhone') !== false) {
            $visitorsPlatform = 'iPhone';
        } elseif (strpos($userAgent, 'Macintosh; Intel Mac OS') !== false) {
            $visitorsPlatform = 'Mac';
        } else {
            $visitorsPlatform = 'Other';
            $data['user_agent'] = $userAgent;
        }

        $data['visitors_platform'] = $visitorsPlatform;

        if (strpos($userAgent, 'Opera') !== false || strpos($userAgent, 'OPR') !== false) {
            $browser = 'Opera';
        } elseif (strpos($userAgent, 'Edge') !== false) {
            $browser = 'Edge';
        } elseif (strpos($userAgent, 'Firefox') !== false) {
            $browser = 'Firefox';
        } elseif (strpos($userAgent, 'Safari') !== false && !strpos($userAgent, 'Chrome') !== false) {
            $browser = 'Safari';
        } elseif (strpos($userAgent, 'Chrome') !== false && strpos($userAgent, 'Edge') === false &&
            (strpos($userAgent, 'Opera') === false || strpos('OPR', $userAgent) === false)) {
            $browser = 'Chrome';
        } elseif (strpos('MSIE', $userAgent) !== false || strpos('Trident', $userAgent) !== false) {
            $browser = 'IE';
        } elseif (strpos($userAgent, 'Mobile') !== false) {
            $browser = 'Mobile';
        }
        $data['browser'] = $browser;
        //查询当天访客是否有访问
        $nowDate = date('Y-m-d',time());
        $startDate = $nowDate.' 00:00:00';
        $endData = $nowDate.' 23:59:59';

        $recordRes = $this->model->getOne([
            ['ip','=',$data['ip']],
            ['referrer','=',$data['referrer']],
            ['create_time','>=',strtotime($startDate)],
            ['create_time','<=',strtotime($endData)],
        ]);
        if (!empty($recordRes)) {
            $id = $recordRes['id'];
            $this->model->where('id',$id)->update(['update_time'=>time()]);
            $this->model->cacheReset($id, [], $id);
        } else {
            $id = $this->model->insertGetId($data);

        }

        //修改访客状态信息
        $logId = $param['log_id'] ?? 0;
        if (!empty($logId)){
            $SendLogService = new SendLogService();
            $SendLogService->emailClickLink(['log_id'=>$logId]);
        }

        return message("操作成功", true, ['record_id' => $id]);

    }
}
